<?php
/**
 * 手动安装脚本
 * 如果自动安装失败，可以使用此脚本手动创建数据库表
 */

// 数据库配置
$db_config = [
    'host' => 'localhost',
    'username' => 'worklog_kukudb_c',
    'password' => '',
    'database' => 'worklog_kukudb_c',
    'charset' => 'utf8mb4'
];

try {
    // 连接数据库
    $dsn = "mysql:host={$db_config['host']};dbname={$db_config['database']};charset={$db_config['charset']}";
    $pdo = new PDO($dsn, $db_config['username'], $db_config['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "数据库连接成功！\n";
    
    // 读取SQL文件
    $sqlFile = __DIR__ . '/sql/database.sql';
    if (file_exists($sqlFile)) {
        $sql = file_get_contents($sqlFile);
        
        // 分割SQL语句
        $queries = array_filter(array_map('trim', explode(';', $sql)));
        
        $successCount = 0;
        $errorCount = 0;
        
        foreach ($queries as $query) {
            if (!empty($query)) {
                try {
                    $pdo->exec($query);
                    echo "✓ 执行成功: " . substr($query, 0, 50) . "...\n";
                    $successCount++;
                } catch (Exception $e) {
                    echo "✗ 执行失败: " . $e->getMessage() . "\n";
                    echo "   SQL: " . substr($query, 0, 100) . "...\n";
                    $errorCount++;
                }
            }
        }
        
        echo "\n安装完成！\n";
        echo "成功: {$successCount} 条\n";
        echo "失败: {$errorCount} 条\n";
        
        if ($errorCount === 0) {
            echo "\n✅ 所有表创建成功！\n";
            echo "默认管理员账号：\n";
            echo "用户名: admin\n";
            echo "密码: admin123\n";
            echo "\n请访问系统首页开始使用。\n";
        } else {
            echo "\n⚠️ 部分表创建失败，请检查错误信息。\n";
        }
        
    } else {
        echo "错误：数据库SQL文件不存在: {$sqlFile}\n";
    }
    
} catch (PDOException $e) {
    echo "数据库连接失败: " . $e->getMessage() . "\n";
    echo "请检查数据库配置：\n";
    echo "主机: {$db_config['host']}\n";
    echo "用户名: {$db_config['username']}\n";
    echo "数据库: {$db_config['database']}\n";
    echo "\n提示：请确保数据库已存在且用户具有创建表的权限。\n";
}
?>
